<template>
  <el-card class="form-container" shadow="never">
    <el-form :model="menu" :rules="rules" ref="menuFormRef" label-width="150px">
      <el-form-item label="菜单名称：" prop="title">
        <el-input v-model="menu.title"></el-input>
      </el-form-item>
      <el-form-item label="上级菜单：">
        <el-select v-model="menu.parentId" placeholder="请选择菜单">
          <el-option
              v-for="item in selectMenuList"
              :key="item.id"
              :label="item.title"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="前端名称：" prop="name">
        <el-input v-model="menu.name"></el-input>
      </el-form-item>
      <el-form-item label="前端图标：" prop="icon">
        <el-input v-model="menu.icon" style="width: 80%"></el-input>
        <svg-icon style="margin-left: 8px" :icon-class="menu.icon"></svg-icon>
      </el-form-item>
      <el-form-item label="是否显示：">
        <el-radio-group v-model="menu.hidden">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序：">
        <el-input v-model="menu.sort"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fetchList, createMenu, updateMenu, getMenu } from '@/api/menu';

const defaultMenu = {
  title: '',
  parentId: 0,
  name: '',
  icon: '',
  hidden: 0,
  sort: 0
};

export default {
  name: "MenuDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const route = useRoute();
    const router = useRouter();
    const menu = ref({ ...defaultMenu });
    const selectMenuList = ref([]);
    const rules = reactive({
      title: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入前端名称', trigger: 'blur' },
        { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
      ],
      icon: [
        { required: true, message: '请输入前端图标', trigger: 'blur' },
        { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
      ]
    });

    const menuFormRef = ref(null);

    const getSelectMenuList = async () => {
      try {
        const response = await fetchList(0, { pageSize: 100, pageNum: 1 });
        selectMenuList.value = response.data.data.list;
        selectMenuList.value.unshift({ id: 0, title: '无上级菜单' });
      } catch (error) {
        console.error('Error fetching menu list:', error);
      }
    };

    const onSubmit = async () => {
      if (!menuFormRef.value) return;

      menuFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            await ElMessageBox.confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });

            if (props.isEdit) {
              await updateMenu(route.query.id, menu.value);
              ElMessage({
                message: '修改成功',
                type: 'success',
                duration: 1000
              });
            } else {
              await createMenu(menu.value);
              ElMessage({
                message: '提交成功',
                type: 'success',
                duration: 1000
              });
              resetForm();
            }

            router.back();
          } catch (error) {
            if (error.message !== 'cancel') {
              console.error('Error submitting form:', error);
              ElMessage({
                message: '提交失败，请重试',
                type: 'error',
                duration: 1000
              });
            }
          }
        } else {
          ElMessage({
            message: '验证失败',
            type: 'error',
            duration: 1000
          });
        }
      });
    };

    const resetForm = () => {
      if (menuFormRef.value) {
        menuFormRef.value.resetFields();
      }
      menu.value = { ...defaultMenu };
      getSelectMenuList();
    };

    onMounted(async () => {
      if (props.isEdit) {
        try {
          const response = await getMenu(route.query.id);
          menu.value = response.data.data;
        } catch (error) {
          console.error('Error fetching menu details:', error);
        }
      }
      await getSelectMenuList();
    });

    return {
      menu,
      selectMenuList,
      rules,
      menuFormRef,
      onSubmit,
      resetForm
    };
  }
};
</script>

<style scoped>
/* Add your styles here */
</style>